package com.xiongwei.thread;

/**
 * JVM允许同一线程重复获取同一个锁,这种能被同一线程反复获取的锁叫做可重入锁;
 *
 * Java的synchronized锁是可重入锁;
 *
 * 死锁产生的条件是多线程各自持有不同的锁,并互相试图获取对象已持有的锁,导致无限等待;
 *
 * 避免死锁的方法是多线程获取锁的顺序要一致;
 *
 * @author XiongWei
 * @date 2021/1/13
 */
public class DeadLock {
    public static void main(String[] args) {
        DeadLockCount dlc = new DeadLockCount();
        Thread t1 = new Thread(() -> {
            dlc.add(1);
            //dlc.dec(1);
        });
        Thread t2 = new Thread(() -> {
            dlc.dec(1);
            //dlc.add(1);
        });
        t1.start();
        t2.start();
    }
}

class DeadLockCount {
    private int count1 = 0;
    private int count2 = 0;

    private Object lockA = new Object();
    private Object lockB = new Object();

    public void add(int m) {
        synchronized (lockA) {
            this.count1 += m;
            System.out.println("count1+:"+count1);
            synchronized (lockB) {
                this.count2 += m;
                System.out.println("count2+:"+count2);
            }
        }
    }

    public void dec(int m) {
        synchronized (lockB) {
            this.count1 -= m;
            System.out.println("count1-:"+count1);
            synchronized (lockA) {
                this.count2 -= m;
                System.out.println("count2-:"+count2);

            }
        }
    }

}
